import Taro from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { AtFab, AtCard } from 'taro-ui'
import { useState, useEffect } from 'react'
import { debtService, debtorService } from '../../utils/cloud'
import { isPaymentCompleted } from '../../utils/calculation'

export default function Debt() {
  const [debts, setDebts] = useState([])
  const [debtors, setDebtors] = useState({})
  const [loading, setLoading] = useState(true)

  // 还款方式映射
  const paymentTypeMap = {
    equalPayment: '等额本息',
    equalPrincipal: '等额本金',
    interestFirst: '先息后本',
    noInterest: '免息'
  }

  useEffect(() => {
    // 加载债务数据和债务人数据
    const loadData = async () => {
      try {
        setLoading(true)
        // 获取债务数据
        const debtsResult = await debtService.getDebts()
        if (!debtsResult.success) {
          throw new Error(debtsResult.error)
        }

        // 获取债务人数据
        const debtorsResult = await debtorService.getDebtors()
        if (!debtorsResult.success) {
          throw new Error(debtorsResult.error)
        }

        // 将债务人数据转换为以id为key的对象，方便查找
        const debtorsMap = debtorsResult.data.reduce((acc, debtor) => {
          acc[debtor._id] = debtor
          return acc
        }, {})

        // 验证债务数据中的债务人是否存在
        const validDebts = debtsResult.data.filter(debt => {
          if (!debt.creditor) {
            console.warn(`债务 ${debt._id} 缺少债务人信息`)
            return false
          }
          if (!debtorsMap[debt.creditor]) {
            console.warn(`债务 ${debt._id} 的债务人 ${debt.creditor} 不存在`)
            return false
          }
          return true
        })

        setDebts(validDebts)
        setDebtors(debtorsMap)
      } catch (error) {
        Taro.showToast({
          title: '数据加载失败',
          icon: 'error'
        })
      } finally {
        setLoading(false)
      }
    }

    loadData()
    // 添加页面显示时的监听，确保从其他页面返回时数据更新
    const onShowHandler = () => loadData()
    Taro.eventCenter.on('PAGE_SHOW', onShowHandler)

    return () => {
      Taro.eventCenter.off('PAGE_SHOW', onShowHandler)
    }
  }, [])

  // 计算总计数据
  const totals = debts.reduce(
    (acc, debt) => {
      // 计算当前日期
      const currentDate = new Date()
      const currentMonth = currentDate.getMonth() + 1
      const currentDay = currentDate.getDate()
      const currentHour = currentDate.getHours()

      // 从还款计划中计算实际剩余金额
      let remainingPrincipal = 0
      let remainingInterest = 0
      let paidTotal = 0
      let paidPrincipal = 0
      let paidInterest = 0
      let unpaidTotal = 0
      let unpaidPrincipal = 0
      let unpaidInterest = 0

      if (debt.calculation?.paymentPlan) {
        debt.calculation.paymentPlan.forEach(plan => {
          const principal = parseFloat(plan.principal || 0)
          const interest = parseFloat(plan.interest || 0)
          const payment = parseFloat(plan.payment || 0)

          // 判断是否已还款（实时计算）
          const isPaid = isPaymentCompleted(plan.paymentDate)

          if (isPaid) {
            // 已还款
            paidTotal += payment
            paidPrincipal += principal
            paidInterest += interest
          } else {
            // 未还款
            remainingPrincipal += principal
            remainingInterest += interest
            unpaidTotal += payment
            unpaidPrincipal += principal
            unpaidInterest += interest
          }
        })
      }

      // 计算当月待还金额
      let monthlyTotal = 0
      let monthlyPrincipal = 0
      let monthlyInterest = 0
      let monthlyPaidTotal = 0
      let monthlyPaidPrincipal = 0
      let monthlyPaidInterest = 0
      let monthlyUnpaidTotal = 0
      let monthlyUnpaidPrincipal = 0
      let monthlyUnpaidInterest = 0

      // 只处理当月的还款计划
      const currentMonthPlans =
        debt.calculation?.paymentPlan?.filter(plan => {
          const planDate = new Date(plan.paymentDate)
          return (
            planDate.getMonth() + 1 === currentMonth &&
            planDate.getFullYear() === currentDate.getFullYear()
          )
        }) || []

      currentMonthPlans.forEach(plan => {
        const principal = parseFloat(plan.principal || 0)
        const interest = parseFloat(plan.interest || 0)
        const payment = parseFloat(plan.payment || 0)

        // 判断是否已还款（实时计算）
        const isPaid = isPaymentCompleted(plan.paymentDate)

        if (isPaid) {
          // 已还款
          monthlyPaidTotal += payment
          monthlyPaidPrincipal += principal
          monthlyPaidInterest += interest
        } else {
          // 未还款
          monthlyUnpaidTotal += payment
          monthlyUnpaidPrincipal += principal
          monthlyUnpaidInterest += interest
        }

        // 当月总还款
        monthlyTotal += payment
        monthlyPrincipal += principal
        monthlyInterest += interest
      })

      // 累加到总计
      acc.totalAmount += remainingPrincipal + remainingInterest
      acc.totalPrincipal += remainingPrincipal
      acc.totalInterest += remainingInterest
      acc.monthlyTotal += monthlyTotal
      acc.monthlyPrincipal += monthlyPrincipal
      acc.monthlyInterest += monthlyInterest
      acc.paidTotal += paidTotal
      acc.paidPrincipal += paidPrincipal
      acc.paidInterest += paidInterest
      acc.unpaidTotal += unpaidTotal
      acc.unpaidPrincipal += unpaidPrincipal
      acc.unpaidInterest += unpaidInterest
      acc.monthlyPaidTotal += monthlyPaidTotal
      acc.monthlyPaidPrincipal += monthlyPaidPrincipal
      acc.monthlyPaidInterest += monthlyPaidInterest
      acc.monthlyUnpaidTotal += monthlyUnpaidTotal
      acc.monthlyUnpaidPrincipal += monthlyUnpaidPrincipal
      acc.monthlyUnpaidInterest += monthlyUnpaidInterest

      return acc
    },
    {
      totalAmount: 0,
      totalPrincipal: 0,
      totalInterest: 0,
      monthlyTotal: 0,
      monthlyPrincipal: 0,
      monthlyInterest: 0,
      paidTotal: 0,
      paidPrincipal: 0,
      paidInterest: 0,
      unpaidTotal: 0,
      unpaidPrincipal: 0,
      unpaidInterest: 0,
      monthlyPaidTotal: 0,
      monthlyPaidPrincipal: 0,
      monthlyPaidInterest: 0,
      monthlyUnpaidTotal: 0,
      monthlyUnpaidPrincipal: 0,
      monthlyUnpaidInterest: 0
    }
  )

  const handleAddDebt = () => {
    Taro.navigateTo({ url: '/pages/debt/index' })
  }

  const handleAddDebt2 = () => {
    Taro.navigateTo({ url: '/pages/reverseDebt/index' })
  }

  const handleNavigateToDebtor = () => {
    Taro.navigateTo({ url: '/pages/debtor/index' })
  }

  if (loading) {
    return (
      <View className="min-h-screen bg-gray-100 flex items-center justify-center">
        <Text className="text-gray-500">加载中...</Text>
      </View>
    )
  }

  return (
    <View className="min-h-screen bg-gray-100 pb-20">
      {/* 总计信息卡片 */}
      <View className="bg-white p-4 mb-4 shadow-sm">
        <Text className="text-lg font-medium block mb-4">债务总览</Text>
        <View className="grid grid-cols-2 gap-4">
          <View className="text-center">
            <Text className="text-sm text-gray-600 block">剩余总欠款</Text>
            <Text className="text-xl text-red-500 font-bold">¥{totals.totalAmount.toFixed(2)}</Text>
          </View>
          <View className="text-center">
            <Text className="text-sm text-gray-600 block">剩余总本金</Text>
            <Text className="text-lg text-blue-500 font-bold">
              ¥{totals.totalPrincipal.toFixed(2)}
            </Text>
          </View>
          <View className="text-center">
            <Text className="text-sm text-gray-600 block">剩余总利息</Text>
            <Text className="text-lg text-orange-500 font-bold">
              ¥{totals.totalInterest.toFixed(2)}
            </Text>
          </View>
        </View>
      </View>

      {/* 当月还款信息卡片 */}
      <View className="bg-gradient-to-r from-blue-500 to-blue-600 p-4 mb-4 text-white">
        <Text className="text-lg font-medium block mb-4">本月还款</Text>
        <View className="grid grid-cols-3 gap-4 mb-4">
          <View className="text-center">
            <Text className="text-sm opacity-80 block">总金额</Text>
            <Text className="text-xl font-bold">¥{totals.monthlyTotal.toFixed(2)}</Text>
          </View>
          <View className="text-center">
            <Text className="text-sm opacity-80 block">本金</Text>
            <Text className="text-lg font-bold">¥{totals.monthlyPrincipal.toFixed(2)}</Text>
          </View>
          <View className="text-center">
            <Text className="text-sm opacity-80 block">利息</Text>
            <Text className="text-lg font-bold">¥{totals.monthlyInterest.toFixed(2)}</Text>
          </View>
        </View>
        <View className="grid grid-cols-2 gap-4">
          <View className="bg-white bg-opacity-10 rounded p-2">
            <Text className="text-sm opacity-80 block">已还</Text>
            <Text className="text-base font-bold">¥{totals.monthlyPaidTotal.toFixed(2)}</Text>
            <Text className="text-xs opacity-80">
              ({totals.monthlyPaidInterest.toFixed(2)}/{totals.monthlyPaidPrincipal.toFixed(2)})
            </Text>
          </View>
          <View className="bg-white bg-opacity-10 rounded p-2">
            <Text className="text-sm opacity-80 block">待还</Text>
            <Text className="text-base font-bold">¥{totals.monthlyUnpaidTotal.toFixed(2)}</Text>
            <Text className="text-xs opacity-80">
              ({totals.monthlyUnpaidInterest.toFixed(2)}/{totals.monthlyUnpaidPrincipal.toFixed(2)})
            </Text>
          </View>
        </View>
      </View>

      {/* 债务列表 */}
      <View className="px-4">
        {debts.map(debt => {
          const debtor = debtors[debt.creditor]
          if (!debtor) {
            return null
          }
          return (
            <View key={debt._id} className="mb-4">
              <AtCard
                title={`${debtor.name}(${debtor.cardNumber ? debtor.cardNumber.slice(-4) : 'XXXX'})`}
                className="shadow-sm"
              >
                <View className="grid grid-cols-2 gap-4">
                  <View>
                    <Text className="text-sm text-gray-600 block">借款本金</Text>
                    <Text className="text-base text-gray-800">
                      ¥{parseFloat(debt.loanAmount).toFixed(2)}
                    </Text>
                  </View>
                  <View>
                    <Text className="text-sm text-gray-600 block">总利息</Text>
                    <Text className="text-base text-gray-800">
                      ¥{parseFloat(debt.totalInterest).toFixed(2)}
                    </Text>
                  </View>
                  <View>
                    <Text className="text-sm text-gray-600 block">还款总额</Text>
                    <Text className="text-base text-gray-800">
                      ¥{parseFloat(debt.totalPayment).toFixed(2)}
                    </Text>
                  </View>
                  <View>
                    <Text className="text-sm text-gray-600 block">还款方式</Text>
                    <Text className="text-base text-gray-800">
                      {paymentTypeMap[debt.paymentType] || '未知'}
                    </Text>
                  </View>
                  <View>
                    <Text className="text-sm text-gray-600 block">借款日期</Text>
                    <Text className="text-base text-gray-800">{debt.loanDate}</Text>
                  </View>
                  <View>
                    <Text className="text-sm text-gray-600 block">还款日期</Text>
                    <Text className="text-base text-gray-800">{debt.paymentDate}号</Text>
                  </View>
                  <View>
                    <Text className="text-sm text-gray-600 block">分期</Text>
                    <Text className="text-base text-gray-800">
                      {debt.remainingPeriods}/{debt.calculation?.paymentPlan?.length || 0}期
                    </Text>
                  </View>
                  <View>
                    <Text className="text-sm text-gray-600 block">年利率</Text>
                    <Text className="text-base text-gray-800">{debt.rate}%</Text>
                  </View>
                </View>
              </AtCard>
            </View>
          )
        })}
      </View>

      {/* 底部导航栏 */}
      <View className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-4 py-2">
        <View className="flex justify-around items-center">
          {/* 债务人按钮 */}
          <View className="flex flex-col items-center" onClick={handleNavigateToDebtor}>
            <View className="w-12 h-12 bg-blue-500 rounded-full flex items-center justify-center mb-1">
              <Text className="text-white text-lg">人</Text>
            </View>
            <Text className="text-xs text-gray-600">债务人</Text>
          </View>

          {/* 添加债务按钮 */}
          <View className="flex flex-col items-center" onClick={handleAddDebt}>
            <View className="w-12 h-12 bg-green-500 rounded-full flex items-center justify-center mb-1">
              <Text className="text-white text-lg">+</Text>
            </View>
            <Text className="text-xs text-gray-600">新借款</Text>
          </View>

          {/* 添加债务按钮 */}
          <View className="flex flex-col items-center" onClick={handleAddDebt2}>
            <View className="w-12 h-12 bg-green-500 rounded-full flex items-center justify-center mb-1">
              <Text className="text-white text-lg">+</Text>
            </View>
            <Text className="text-xs text-gray-600">新借款2</Text>
          </View>
        </View>
      </View>
    </View>
  )
}
